<template>
  <div class="app-container">
    <div class="app-head">
      <el-form>
        <el-row type="flex" justify="start">
          <el-col :span="15">
            <el-form-item label="用户ID" label-width="100px">
              <el-input v-model="userId" style="width:50%" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item v-show="platformArr.length > 1" label="所属业务平台" label-width="100px">
              <el-select v-model="platform" style="width:90%" size="mini" placeholder="请选择">
                <el-option value="" label="全部" />
                <el-option v-for="item of platformArr" :key="item.idVal" :value="item.idVal" :label="item.powerName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1" class="absolute main-button">
            <el-button
              v-powerbtn="{power:'datamonit-user-search'}"
              size="mini"
              round
              type="primary"
              icon="el-icon-search"
              @click="loadList"
            >查询</el-button>
          </el-col>
        </el-row>

        <el-row type="flex" justify="start">
          <el-col :span="15">
            <el-form-item label="信息同步时间" label-width="100px">
              <el-date-picker
                v-model="startDate"
                :picker-options="pickerOptions1"
                :editable="false"
                type="datetime"
                size="mini"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss   "
                placeholder="选择开始时间"
                class="timeLength"
                @change="checkStartTime"
              />
              至
              <el-date-picker
                v-model="endDate"
                :picker-options="pickerOptions2"
                :editable="false"
                type="datetime"
                size="mini"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss   "
                placeholder="选择结束时间"
                class="timeLength"
                @change="checkTime"
              />
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="信息同步状态" label-width="100px">
              <el-select v-model="faStatus" style="width:90%" size="mini" placeholder="请选择">
                <el-option value="" label="全部" />
                <el-option v-for="item of serviceTypeArr" :key="item.configValue" :value="item.configValue" :label="item.configKeyDown" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1" class="absolute main-button">
            <el-button
              size="mini"
              round
              icon="el-icon-refresh"
              @click="reset"
            >
              重置
            </el-button>
          </el-col>

        </el-row>
      </el-form>
    </div>
    <el-button
      v-powerbtn="{power:'datamonit-user-search'}"
      size="mini"
      type="primary"
      round
      style="margin-top:10px;margin-bottom: 5px;"
      @click="refresh"
    >重新执行工单</el-button>
    <div class="app-table">
      <el-table
        :data="list"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column label="用户ID">
          <template slot-scope="scope">
            <el-popover v-if="scope.row.onlyFlag" :content="scope.row.onlyFlag" placement="top" trigger="hover">
              <span slot="reference" style="cursor:pointer">{{ scope.row.onlyFlag }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="所属业务平台">
          <template slot-scope="scope">
            <el-popover v-if="scope.row.platName" :content="scope.row.platName" placement="top" trigger="hover">
              <span slot="reference" style="cursor:pointer">{{ scope.row.platName }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="信息同步状态">
          <template slot-scope="scope">
            {{ scope.row.flagName }}
          </template>
        </el-table-column>
        <el-table-column label="信息同步时间">
          <template slot-scope="scope">
            <el-popover v-if="scope.row.lastTime" :content="scope.row.lastTime" placement="top" trigger="hover">
              <span slot="reference" style="cursor:pointer">{{ scope.row.lastTime }}</span>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination :current-page="pageid" :page-sizes="[20,50,100]" :page-size="pagecount" :total="count" background highlight-current-row layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- <watch-info :watch-dialog="watchDialog" :watch-id="watchId" @closeWatch="closeWatch" />
    <watch-connect :edit-dialog="editDialog" :watch-id="watchId" @closeConect="closeConect" /> -->
  </div>
</template>

<script>
import { getList, repeat, config } from '@/api/userMonit.js'
// import { getSelect } from '@/api/services.js'
import { mapGetters } from 'vuex'
import powerbtn from '@/directive/powerbtn/index.js'
/* import watchInfo from './components/watchInfo.vue'
import watchConnect from './components/hasConnect.vue' */
export default {
  directives: {
    powerbtn
  },
  /*  components: {
    watchInfo: watchInfo,
    watchConnect: watchConnect
  }, */
  data() {
    return {
      list: [], // 请求列表
      faStatus: '',
      userId: '',
      serviceId: '',
      flag: true,
      serviceType: '',
      monitId: '',
      platformId: '',
      platform: '',
      platformArr: [],
      name: '', // 服务名称
      source: '', // 服务来源
      pay: [], // 支付渠道下拉
      pageid: 1, // 当前页数
      pagecount: 20, // 每页可显示条数
      status: false, // 请求状态
      watchDialog: false, // 查看遮罩
      editDialog: false, // 编辑遮罩
      watchId: '0', // 策略id
      count: 0, // 总数量
      paySelect: [],
      serviceTypeArr: [],
      sourceArr: [],
      arr: [], // 多选
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      pickerOptions2: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      startDate: '',
      endDate: ''
    }
  },
  computed: {
    ...mapGetters(['plat'])
  },
  mounted() {
    this.platformArr = this.plat
    if (this.platformArr.length > 1) {
      this.platformArr.forEach(item => {
        var len = item.powerCode.lastIndexOf('-')
        item.idVal = item.powerCode.substr(len + 1)
      })
      this.getSelectAll()
    }
    if (this.platformArr.length === 1) {
      var sina = this.platformArr[0].powerCode.lastIndexOf('-')
      this.platformId = this.platformArr[0].powerCode.substr(sina + 1)
      this.getSelectAll(true)
    }
  },
  methods: {
    refresh() {
      if (this.monitId.length < 1) {
        this.$message({
          type: 'error',
          message: '请选择工单'
        })
        return false
      }
      var data = {
        queryType: '0',
        ids: this.monitId.join(',')
      }
      this.$confirm('确定要重新执行工单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        repeat(data).then(res => {
          if (res.resultCode === '0000') {
            this.$message({
              type: 'success',
              message: '执行成功'
            })
            this.loadList()
          }
        })
      }).catch(() => {
        console.log('执行取消')
      })
    },
    // 请求列表
    loadList(status) {
      this.pageid = 1
      this.pageid = 1
      if (status === true) {
        this.platform = this.platformId
      }
      const request = {
        onlyFlag: this.userId,
        name: this.name,
        platformId: this.platform,
        flag: this.faStatus,
        beginTime: this.startDate,
        endTime: this.endDate,
        lspid: '',
        cspid: '',
        queryType: '0',
        pageNum: 1, // 当前页数
        limit: 20 // 每页可显示条数
      }
      getList(request).then(res => {
        if (res.resultCode === '0000') {
          this.list = res.data.list
          this.count = parseInt(res.data.total) // 总数量
          if (this.list.length > 0) {
            this.serviceTypeArr.forEach(num => {
              this.list.forEach(item => {
                if (item.flag == num.configValue) { // eslint-disable-line
                  item.flagName = num.configKeyDown
                }
              })
            })
            // this.pageid = parseInt(res.data.list[0].pageNum) // 当前页数
          }
          this.status = true
        }
      }).catch(() => {
        this.$message({
          message: '请求列表失败',
          type: 'error'
        })
      })
    },
    handleSelectionChange(val) {
      console.log(val)
      if (val.length > 0) {
        this.monitId = val.map(item => {
          return item.id
        })
      }
      if (val.length === 0) {
        this.monitId = []
      }
    },
    // 校验开始时间
    checkStartTime(time) {
      const reg = new RegExp('-', 'g')
      // 比较是否大于现在的时间
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.startDate = ''
          }
        })
      } else {
        if (!!time) {  // eslint-disable-line
          var end
          if (this.endDate !== null) {
            end = new Date(this.endDate.replace(reg, '/')).getTime()
          } else {
            end = ''
          }
          var first = new Date(time.replace(reg, '/')).getTime()
          if (!!end && first > end) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.startDate = ''
          }
        }
      }
    },

    // 校验结束时间
    checkTime(time) {
      const reg = new RegExp('-', 'g')
      // console.log(newStr)
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.endDate = ''
          }
        })
      } else {
        if (!!time) {  // eslint-disable-line
          var start
          if (this.startDate !== null) {
            start = new Date(this.startDate.replace(reg, '/')).getTime()
          } else {
            start = ''
          }
          var end = new Date(time.replace(reg, '/')).getTime()
          if (end < start) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.endDate = ''
          }
        }
      }
    },
    connect(id) {
      this.editDialog = true
      this.watchId = id
    },

    closeConect() {
      this.editDialog = false
    },
    // 请求支付渠道下拉
    getSelectAll(status) {
      // 服务类型
      var data = {
        configKey: 'flag'
      }
      config(data).then(res => {
        if (res.resultCode === '0000') {
          this.serviceTypeArr = res.data
          this.loadList(status)
        }
      })
    },

    reset() {
      if (this.platformArr.length !== 1) {
        this.platform = ''
      }
      this.userId = ''
      this.faStatus = ''
      this.serviceId = ''
      this.name = ''
      this.source = ''
      this.serviceType = ''
      this.startDate = ''
      this.endDate = ''
    },
    // 当前页面显示条数改变时
    handleSizeChange(num) {
      this.flag = false
      const request = {
        onlyFlag: this.userId,
        name: this.name,
        platformId: this.source,
        flag: this.faStatus,
        beginTime: this.startDate,
        endTime: this.endDate,
        lspid: '',
        cspid: '',
        queryType: '0',
        pageNum: 1, // 当前页数
        limit: num // 每页可显示条数
      }
      console.log('请求数据')
      console.log(request)
      getList(request).then(res => {
        this.list = res.data.list // 列表项
        if (this.list.length > 0) {
          this.serviceTypeArr.forEach(num => {
            this.list.forEach(item => {
              if (item.flag == num.configValue) { // eslint-disable-line
                item.flagName = num.configKeyDown
              }
            })
          })
        // this.pageid = parseInt(res.data.list[0].pageNum) // 当前页数
        }
        this.count = parseInt(res.data.total) // 总数量
        // this.pagecount = num
        this.flag = true
      })
    },

    // 跳转某页
    handleCurrentChange(num) {
      this.pageid = num // 当前页数
      console.log(num)
      const request = {
        onlyFlag: this.userId,
        name: this.name,
        platformId: this.source,
        flag: this.faStatus,
        beginTime: this.startDate,
        endTime: this.endDate,
        lspid: '',
        cspid: '',
        queryType: '0',
        pageNum: num, // 当前页数
        limit: this.pagecount // 每页可显示条数
      }
      console.log('请求数据')
      console.log(request)
      if (this.flag === true) {
        getList(request).then(response => {
          this.list = response.data.list // 列表项
          if (this.list.length > 0) {
            this.serviceTypeArr.forEach(num => {
              this.list.forEach(item => {
                if (item.flag == num.configValue) { // eslint-disable-line
                  item.flagName = num.configKeyDown
                }
              })
            })
            // this.pageid = parseInt(response.data.list[0].pageNum) // 当前页数
          }
          this.count = parseInt(response.data.total) // 总数量
          console.log('返回数据')
          console.log(response.data)
        })
      }
    },

    // 查看
    watch(id) {
      this.watchDialog = true
      this.watchId = id
    },

    edit(id) {
      this.editDialog = true
      this.watchId = parseInt(id)
      this.paySelect = this.pay
    },

    // 关闭查看回调
    closeWatch() {
      this.watchDialog = false
    },

    // 新增
    add() {
      this.addDialog = true
      this.paySelect = this.pay
    },

    // 关闭新增回调
    closeAdd() {
      this.addDialog = false
    },

    closeEdit() {
      this.editDialog = false
    }
  }
}
</script>

<style scoped>
.addBtns{
  margin: 5px 0;
}
.timeLength{
  width: 37.5% !important;
}
</style>
